package cc.admin.modules.graduate.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.aspect.annotation.AutoLog;
import cc.admin.common.sys.base.controller.BaseController;
import cc.admin.common.sys.query.QueryGenerator;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.modules.graduate.entity.Category;
import cc.admin.modules.graduate.entity.ChoiceQuestions;
import cc.admin.modules.graduate.service.IChoiceQuestionsService;
import cc.admin.modules.sys.entity.SysCascade;
import cc.admin.modules.sys.service.ISysCascadeService;
import cc.admin.modules.graduate.entity.ChoiceErrorQuestions;
import cc.admin.modules.graduate.service.IChoiceErrorQuestionsService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 选择题
 * @Author: cc-admin
 * @Date: 2025-02-06
 * @Version: V1.0.0
 */
@Slf4j
@Api(tags = "选择题")
@RestController
@RequestMapping("/choice/errorQuestions")
public class ChoiceErrorQuestionsController extends BaseController<ChoiceErrorQuestions, IChoiceErrorQuestionsService> {
    @Autowired
    private IChoiceErrorQuestionsService choiceErrorQuestionsService;

    @Autowired
    private IChoiceQuestionsService choiceQuestionsService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 分页列表查询
     *
     * @param key
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "选择题-分页列表查询")
    @ApiOperation(value = "选择题-分页列表查询", notes = "选择题-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
            @RequestParam(name = "key", required = false) String key,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        QueryWrapper<ChoiceErrorQuestions> queryWrapper = QueryGenerator.initQueryWrapper(new ChoiceErrorQuestions(), req.getParameterMap());
        if (StrUtil.isNotEmpty(key)) {
            queryWrapper.like("question",key);
        }
        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] catalogs = parameterMap.get("catalog");
        String tab = catalogs[0];
        queryWrapper.eq("subject_id", tab);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("user_id", user.getUsername());

        Page<ChoiceErrorQuestions> page = new Page<ChoiceErrorQuestions>(pageNo, pageSize);
        IPage<ChoiceErrorQuestions> pageList = choiceErrorQuestionsService.page(page, queryWrapper);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT cq.id,cq.question, COUNT(ceq.question_id) AS error_count FROM choice_questions cq LEFT JOIN choice_error_questions ceq ON cq.id = ceq.question_id WHERE cq.viedo_url2 IS NULL AND ceq.question_id IS NOT NULL GROUP BY cq.id, cq.question ORDER BY error_count DESC");
        System.out.println(maps);
        return Result.ok(pageList);
    }

    @ApiOperation(value = "获取没有视频的选择题", notes = "获取没有视频的选择题")
    @GetMapping(value = "/getNoVideoQuestion")
    public Result<?> getErrorWithNoUrl(@RequestParam(name = "key", required = false) String key,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        // 计算偏移量
        int offset = (pageNo - 1) * pageSize;

        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] catalogs = parameterMap.get("catalog");

        String value = null;
        if (catalogs != null && !catalogs[0].equals("")) {
            String tab = catalogs[0];
            value = (String) JSONObject.parseObject(tab).get("value");
        }
        // 修改 SQL 查询，添加 LIMIT 和 OFFSET 子句实现分页
        String sql = "";
        if (value == null) {
            sql = "SELECT cq.id, cq.question, COUNT(ceq.question_id) AS error_count " +
                    "FROM choice_questions cq " +
                    "LEFT JOIN choice_error_questions ceq ON cq.id = ceq.question_id " +
                    "WHERE cq.viedo_url2 IS NULL AND ceq.question_id IS NOT NULL and cq.subject_id=? " +
                    "GROUP BY cq.id, cq.question " +
                    "ORDER BY error_count DESC " +
                    "LIMIT ? OFFSET ?";
        } else {
            sql = "SELECT cq.id, cq.question, COUNT(ceq.question_id) AS error_count " +
                    "FROM choice_questions cq " +
                    "LEFT JOIN choice_error_questions ceq ON cq.id = ceq.question_id " +
                    "WHERE cq.viedo_url2 IS NULL AND ceq.question_id IS NOT NULL and cq.subject_id=? and cq.major_id like ?" +
                    "GROUP BY cq.id, cq.question " +
                    "ORDER BY error_count DESC " +
                    "LIMIT ? OFFSET ?";
        }

        // 执行分页查询
        List<Map<String, Object>> maps = null;
        if (value != null) {
            maps = jdbcTemplate.queryForList(sql, key, value, pageSize, offset);
        } else {
            maps = jdbcTemplate.queryForList(sql, key, pageSize, offset);

        }
        System.out.println(maps);

        // 处理查询结果
        ArrayList<ChoiceQuestions> questions = new ArrayList<>();
        maps.forEach(choiceErrorQuestion -> {
            String id = (String) choiceErrorQuestion.get("id");
            ChoiceQuestions choiceQuestions = choiceQuestionsService.getById(id);
            choiceQuestions.setErroeTotal(choiceErrorQuestion.get("error_count").toString());
            // 定义每个选择题里面的下拉框
            ArrayList<Category> categories = new ArrayList<>();
            //当存在下拉数据时
            if (choiceQuestions.getCategoryIds() != null && choiceQuestions.getCategoryIdsText() != null) {
                String[] split = choiceQuestions.getCategoryIds().split(",");
                String[] split2 = choiceQuestions.getCategoryIdsText().split(",");
                for (int i = 0; i < split.length; i++) {
                    Category category = new Category(split[i], split2[i]);
                    categories.add(category);
                }
            }
            choiceQuestions.setCategorys(categories);
            questions.add(choiceQuestions);
        });

        // 创建分页对象
        Page<ChoiceQuestions> page = new Page<>(pageNo, pageSize);
        page.setRecords(questions);

        // 计算总记录数
        String countSql = "SELECT COUNT(DISTINCT cq.id) " +
                "FROM choice_questions cq " +
                "LEFT JOIN choice_error_questions ceq ON cq.id = ceq.question_id " +
                "WHERE cq.viedo_url2 IS NULL AND ceq.question_id IS NOT NULL";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class);
        page.setTotal(total);

        return Result.ok(page);
    }

    /**
     * 添加
     *
     * @param choiceErrorQuestions
     * @return
     */
    @AutoLog(value = "选择题-添加")
    @ApiOperation(value = "选择题-添加", notes = "选择题-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ChoiceErrorQuestions choiceErrorQuestions) {
        choiceErrorQuestions.setId(IdUtil.objectId());
        choiceErrorQuestionsService.save(choiceErrorQuestions);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param choiceErrorQuestions
     * @return
     */
    @AutoLog(value = "选择题-编辑")
    @ApiOperation(value = "选择题-编辑", notes = "选择题-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ChoiceErrorQuestions choiceErrorQuestions) {
        choiceErrorQuestionsService.updateById(choiceErrorQuestions);
        return Result.ok("编辑成功!");
    }


    /**
     * 复制
     *
     * @param id
     * @param name
     * @return
     */
    @AutoLog(value = "选择题-复制")
    @ApiOperation(value = "选择题-复制", notes = "选择题-复制")
    @PostMapping(value = "/copy")
    public Result<?> copy(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "name", required = true) String name) {
        ChoiceErrorQuestions choiceErrorQuestions = choiceErrorQuestionsService.getById(id);
        choiceErrorQuestions.setId(IdUtil.fastUUID());
        choiceErrorQuestions.setCreateTime(new Date());
        choiceErrorQuestionsService.save(choiceErrorQuestions);
        return Result.ok("复制成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "选择题-通过id删除")
    @ApiOperation(value = "选择题-通过id删除", notes = "选择题-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        choiceErrorQuestionsService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "选择题-批量删除")
    @ApiOperation(value = "选择题-批量删除", notes = "选择题-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.choiceErrorQuestionsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "选择题-通过id查询")
    @ApiOperation(value = "选择题-通过id查询", notes = "选择题-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ChoiceErrorQuestions choiceErrorQuestions = choiceErrorQuestionsService.getById(id);
        return Result.ok(choiceErrorQuestions);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param choiceErrorQuestions
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChoiceErrorQuestions choiceErrorQuestions) {
        return super.exportXls(request, choiceErrorQuestions, ChoiceErrorQuestions.class, "选择题");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChoiceErrorQuestions.class);
    }

}
